import { axiosService as Axios } from 'src/boot/api';
import router, { resetRouter } from 'src/router';

export default {
  namespaced: true,
  state: {
    mobile: false,
    routes: [],
    auth: [],
    allAuth: [],
    routeTabs: [],
  },
  getters: {
    confirmAuth(s) {
      return (v) => {
        // 权限设置了
        if (s.allAuth.some((au) => au.action === v)) {
          // 这里看用户有没有
          return s.auth.some((au) => au.action === v);
        }
        return true;
      };
    },
  },
  mutations: {
    updateMobile(s, v) {
      s.mobile = v;
    },
    updateRoutes(s, v) {
      s.routes = v;
    },
    updateAuth(s, v) {
      s.auth = v;
    },
    updateAllAuth(s, v) {
      s.allAuth = v;
    },
    addRouteTabs(s, v) {
      if (!s.routeTabs.find((r) => r.fullPath === v.fullPath)) {
        s.routeTabs.push(v);
        if (s.routeTabs.length === 11) {
          s.routeTabs.splice(s.routeTabs.indexOf(s.routeTabs[1]), 1);
        }
      }
    },
    updateRouteTabs(s, v) {
      if (!s.routeTabs.find((r) => r.fullPath === v.fullPath)) {
        const ind = s.routeTabs.findIndex((r) => r.name === v.name);
        if (ind !== -1) {
          s.routeTabs.splice(ind, 1);
          this.$router.replace(v.fullPath);
        }
      }
    },

    removeRouteTabs(s, p) {
      s.routeTabs.splice(s.routeTabs.findIndex((r) => r.fullPath === p), 1);
    },
    clearRouteTabs(s) {
      s.routeTabs = [];
    },
    clear(s) {
      s.routes = [];
      s.auth = [];
      s.allAuth = [];
      s.routeTabs = [];
    },

  },
  actions: {
    dynamicRoutes({ commit, state }) {
      return new Promise((resolve, reject) => {
        Axios.get(`/sys/permission/getUserPermissionByToken?token=${localStorage.Authorization}`).then(({ result: { menu, auth, allAuth } }) => {
          if (menu.length === 0) {
            delete localStorage.Authorization;
            alert('该用户没有分配角色，请联系管理员配置！');
            resetRouter();
            return;
          }
          // 对于手机端的菜单来说这里要把菜单拉平
          // 这里先把不需要显示的菜单过滤掉
          const filterMenu = (arr) => {
            const result = [];
            arr.forEach((v) => {
              if ((window.mobile && v.showPhone) || (!window.mobile && v.showPc)) {
                if (v.children && v.children.length > 0) {
                  v.children = filterMenu(v.children);
                }
                result.push(v);
              }
            });
            return result;
          };
          const filtedMenuList = filterMenu(menu);
          // 菜单转换component动态import
          const imTr = (arr) => {
            const result = [];
            arr.forEach((v) => {
              if (v.meta.fullLayout) {
                router.addRoute({
                  path: '/',
                  component: () => import('layouts/h5'),
                  children: [{
                    ...v,
                    component: () => import(`pages/${v.component}`),
                    children: null,
                  }],
                });
              } else if (!window.mobile && v.showPc) {
                result.push({
                  ...v,
                  component: () => import(`pages/${v.component}`),
                  children: v.children ? imTr(v.children) : null,
                });
              }
            });
            return result;
          };
          const defaultLayoutMenu = imTr(filtedMenuList);
          // 存入store
          commit('updateRoutes', filtedMenuList);
          commit('updateAuth', auth);
          commit('updateAllAuth', allAuth);
          defaultLayoutMenu.forEach((item) => {
            if (!item.meta.fullLayout) {
              router.addRoute({
                path: '/',
                redirect: `${window.mobile ? '/phone/home' : '/sub-system'}`,
                component: window.mobile ? () => import('layouts/phone') : () => import('layouts'),
                children: [item],
              });
            }
          });
          resolve();
        }).catch(() => {
          delete localStorage.Authorization;
          reject();
        });
      });
    }
  },
};
